const fp = require("lodash/fp");
const _ = require("lodash");
const { Maybe, Container } = require("./support");
const { toNumber } = require("lodash");

// 练习1: 使用fp.add(x, y) 和 fp.map(f,x)创建一个能让functor里的值增加的函数ex1
let maybe = Maybe.of([5, 6, 1]);
let ex1 = () => {
  return (increment) => maybe.map((item) => fp.map((val) => fp.add(val, toNumber(increment) || 0), item));
};
console.log(ex1()(10));


// 练习2: 实现一个函数ex2, 能够使用fp.first获取列表的第一个元素
const xs = Container.of(["do", "ray", "me", "fa", "so", "la", "ti", "do"]);
let ex2 = () => (ct) => (ct instanceof Container ? ct.map(fp.first) : fp.first(ct));
const first = ex2();
console.log(first(xs));
// console.log(first(['lagou', 'great']));


// 练习3: 实现一个函数ex3，使用safeProp和fp.first找到user的名字的首字母
let safeProp = fp.curry(function (x, o) {
  return Maybe.of(o[x]);
});
let user = { id: 2, name: "Albert" };
let ex3 = () => (x, o) => safeProp(x, o).map(fp.first);
const firstLetter = ex3();
console.log(firstLetter("name", user));


// 练习4: 使用Maybe重写ex4，不要有if语句
// let ex4 = function (n) {
//   if (n) {
//     return parseInt(n);
//   }
// };
let ex4 = (n) => Maybe.of(n).map(_.parseInt);
console.log(ex4(0));
